package com.clip.service;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.clip.dao.UsermobileinfoDAO;
import com.clip.entity.User;
import com.clip.entity.Usermobileinfo;

@Service
@Transactional
public class UsermobileinfoService {
	@Autowired
	private UsermobileinfoDAO usermobileinfoDAO;
	
	/**
	 * @param mobilenum
	 * @param uid
	 * @return 0: 手机号未被绑定
	 * 		   1: 手机号已被使用	
	 */
	public boolean isMobileBindable(String mobilenum){
		String query="from Usermobileinfo info where info.mobilenum='"+mobilenum+"' and info.status=1";
		List list=usermobileinfoDAO.findByQuery(query);
		if(list==null||list.size()<=0){
			return false;
		}else{
			return true;
			
		}
	}
	
	public boolean isHasBindableMobile(Integer uid){
		String query="from Usermobileinfo info where info.uid="+uid+" and info.status=1";
		List list=usermobileinfoDAO.findByQuery(query);
		if(list==null||list.size()<=0){
			return false;
		}else{
			return true;
			
		}
	}
	
	public void bindMobileWithUser(String mobilenum,User user){
		Usermobileinfo usermobileinfo=new Usermobileinfo();
		usermobileinfo.setUid(user.getId());
		usermobileinfo.setUsername(user.getName());
		usermobileinfo.setMobilenum(mobilenum);
		usermobileinfo.setStatus(1);
		usermobileinfo.setAddtime(new Date().getTime());
		this.usermobileinfoDAO.save(usermobileinfo);
	}

	public String getBindableMobile(Integer uid) {
		String query="from Usermobileinfo info where info.uid="+uid+" and info.status=1";
		List list=usermobileinfoDAO.findByQuery(query);
		if(list==null||list.size()<=0){
			return "";
		}else{
			Usermobileinfo usermobileinfo=(Usermobileinfo) list.get(0);
			return usermobileinfo.getMobilenum();
		}
	}

	public void resetBindableMobile(Integer uid) {
		String query="update Usermobileinfo info set info.status=0 where info.uid="+uid+" and info.status=1";
		usermobileinfoDAO.excueteBatchUpdate(query);
	}
}
